/**
 * 公共js各种方法
 */
;layui.define(['layer', 'form', 'flow'], function (exports) {
    var ly = layui.layer,
        o = layui.jquery,
        flow = layui.flow,
        layTpl = layui.laytpl,
        u = layui.util,
        c = layui.carousel,
        _cacheTable = 'h5-methods-cache';
    var methods = {
        /**
         * 主动触发事件
         * @param type
         */
        event: {
            click: function (filter, ...callback) {
                return methods.event.getEventFunction('lay-click', filter, ...callback);
            },
            change: function (filter, ...callback) {
                return methods.event.getEventFunction('lay-change', filter, ...callback);
            },
            photo: function (title, val) {
                var data = [];
                val.forEach(function (v, i) {
                    data.push({"alt": title, "pid": i, "src": v,})
                })
                ly.photos({photos: {"title": title, "start": 0, "data": data}, footer: false});
            },
            getEventFunction: function (attr, filter, ...callback) {
                var map = {};
                Array.isArray(filter) ? filter.forEach(function (v, i) {
                    map[v] = getFunction(i);
                }) : map[filter] = getFunction(0);

                function getFunction(i = 0) {
                    return function () {
                        var that = o(this), data = that[0].dataset, index;
                        if (attr === 'lay-change') {
                            var cls = data.key ? data.key : 'lay-this';
                            if (data.hasOwnProperty('checkbox')) {
                                that.hasClass(cls) ? that.removeClass(cls) : that.addClass(cls);
                            } else {
                                that.addClass(cls).siblings().removeClass(cls);
                            }

                        }
                        index = callback.length > 1 ? i : 0
                        typeof callback[index] === 'function' ? callback[index](data, that) : '';
                    }
                }

                u.on(attr, map)
            },

        },
        popup: {
            payPassword: function (callback) {
                var css, html, text = o(this).text() ? o(this).text() : '确认';
                css = '.hide-dom {display: none;}  .password-pop {background-color: var(--ff);display: flex;flex-direction: column;align-items: center;padding: .2rem 0;}';
                css += '.password-pop .title {font-size: .32rem;font-weight: bold;color: var(--dcl);margin: 0.1rem 0 .3rem 0;}';
                css += '.password-pop .content {width: calc(100% - .6rem);display: flex;padding: 0 .3rem;}';
                css += '.password-pop .content .inp {font-size: var(--default-font-size-26);color: var(--dcl);padding: .2rem;flex: 1;margin: .3rem 0;border: 1px solid var(--ee);border-radius: .1rem;}';
                html = '<div class="hide-dom">';
                html += '<div class="password-pop"><div class="title">请填写支付密码</div><div class="content"><input type="password" class="inp pay_password" placeholder="请填写支付密码"/></div>';
                html += '<div class="btn theme-btn confirm">' + text + '</div></div>';
                !o('.openPayPassword').length ? o('html').append('<style class="openPayPassword">' + css + '</style>') : '';
                !o('.hide-dom').length ? o('body').append(html) : '';
                ly.open({
                    type: 1,
                    offset: 'b',
                    anim: 'slideUp',
                    area: ['100%', o('.hide-dom').height() + 'px'],
                    title: false,
                    closeBtn: 0,
                    shade: 0.3,
                    shadeClose: true,
                    content: o('.hide-dom'),
                    success: function (layero, index, that) {
                        o(layero).css('border-radius', '0.2rem 0.2rem 0 0');
                        o(layero).find('.layui-layer-content').css('border-radius', '0.2rem 0.2rem 0 0');
                        o('.password-pop .confirm').click(function () {
                            var val = o('.password-pop .pay_password').val();
                            if (!val) {
                                ly.msg('请填写支付密码');
                                return false;
                            }
                            if (typeof callback === 'function') {
                                return callback(val, index)
                            } else {
                                console.error('未配置回调函数');
                            }
                        });
                    }
                });
            }
        },

        /**
         * 加载层
         * @param type
         */
        load: function (type = 2) {
            ly.load(type, {shade: 0.2, time: 0});
        },
        /**
         * 关闭加载层
         */
        closeLoad: function () {
            ly.closeAll('loading');
        },

        /**
         * 渲染轮播图
         */
        renderCarousel: function (elem, mixed, change) {
            mixed = mixed || {};
            mixed.elem = elem;
            mixed.width = mixed.width || 'auto'
            mixed.height = mixed.height || 'auto'
            mixed.interval = mixed.interval || 4000
            mixed.anim = mixed.anim || 'default'
            mixed.indicator = mixed.indicator || 'inside'
            mixed.arrow = mixed.arrow || 'none'
            if (change && typeof change === 'function') {
                mixed.change = function (obj) {
                    change(obj);
                }
            }
            c.render(mixed);
        },

        /**
         * 底部弹出层
         * @param elem
         * @param callback
         */
        popupSlideUp: function (elem, callback) {
            ly.open({
                type: 1,
                offset: 'b',
                anim: 'slideUp',
                area: ['100%', elem.height() + 30 + 'px'],
                title: false,
                closeBtn: 0,
                shade: 0.3,
                shadeClose: true,
                content: elem,
                success: function (layero, index, that) {
                    callback !== undefined ? callback(layero, index, that) : '';
                }
            });
        },
        /**
         * POST请求
         * @param url - url
         * @param data - 提交数据
         * @param callback - 回调函数，可选
         */
        fetchPost: function (url, data, callback) {
            methods.load();
            o.post(url, data, function (d) {
                methods.closeLoad();
                if (typeof callback === 'function') {
                    return callback(d)
                } else {
                    if (d.code === 1) {
                        d.url ? location.href = d.url : (d.msg ? ly.msg(d.msg, {time: 1000}, function () {
                            location.reload()
                        }) : location.reload());
                    } else {
                        ly.msg(d.msg)
                    }
                }
            });
        },
        /**
         * POST请求 - 节流防抖，默认2秒不重复执行
         * @param url - url
         * @param data - 提交数据
         * @param callback - 回调函数，可选
         */
        fetchPostThrottle: layui.throttle(function (url, data, callback) {
            return methods.fetchPost(url, data, callback);
        }, 2000),

        /**
         * GET请求
         * @param url
         * @param data
         * @param callback
         * @param load
         */
        fetchGet: function (url, data, callback, load = true) {
            load ? methods.load() : '';
            o.get(url, data, function (d) {
                load ? methods.closeLoad() : '';
                if (typeof callback === 'function') {
                    return callback(d)
                } else {
                    if (d.code !== 1) d.msg ? ly.msg(d.msg) : '';
                }
            });
        },

        /**
         * 获取流数据
         * @param url
         * @param mixed
         * @param callback
         */
        getFlowData: function (url, mixed, callback) {
            var elem, tpl, end, isLazyimg, mb, scrollElem = '';
            if (typeof mixed === 'function') {
                elem = 'tpl_list';
                tpl = 'template';
                end = '暂无更多';
                isLazyimg = true;
                mb = 50
            } else {
                mixed = mixed || {};
                elem = mixed.elem || 'tpl_list';
                tpl = mixed.tpl || 'template';
                end = mixed.end || '暂无更多';
                isLazyimg = mixed.isLazyimg || true;
                mb = mixed.mb || 50
                scrollElem = mixed.scrollElem || '';
            }
            o("." + elem).html('');
            flow.load({
                elem: '.' + elem
                , isLazyimg: isLazyimg
                , mb: mb
                , scrollElem: scrollElem
                , end: '<div class="layui-flow-more" >' + end + '</div>'
                , done: function (page, next) {
                    methods.fetchGet(url, {page: page}, function (data) {
                        if (data.code === 1) {
                            if (data.data.length > 0) {
                                layTpl(o('#' + tpl).html()).render({
                                    data: data.data,
                                    page: data.page,
                                }, function (html) {
                                    next(html, page < data.pages);
                                });
                            } else {
                                next('', page < data.pages);
                            }
                            typeof mixed === 'function' ? mixed(data) : (callback !== undefined ? callback(data) : '');
                        } else {
                            ly.msg('加载失败');
                        }
                    });

                }
            });
        },

        /**
         * 监听和发送验证码功能
         * @param mixed
         * @param callback
         */
        listenSendMobileCaptcha: function (mixed, callback) {
            var time, cache, elem, url, mobile, text, nowTime, query, cacheKey = 'sendMobileCaptchaCountDown';
            mixed = mixed || {};
            elem = mixed.elem || '';
            url = mixed.url || '';
            mobile = mixed.mobile || '';
            time = mixed.time || 60;
            text = o(elem).text();
            nowTime = true;
            cache = mixed.hasOwnProperty('cache') ? mixed.cache : true;
            if (!elem) throw "未指定elem参数";
            if (!url) throw "未指定url参数";
            if (!mobile) throw "未指定mobile参数";

            cache ? onLoad() : '';

            o(elem).click(layui.throttle(function (that) {
                if (cache) {
                    var timeRemaining = getCountdown();
                    if (!timeRemaining || timeRemaining <= 0) {
                        if (!o(mobile).val()) {
                            ly.msg('请填写手机号');
                            return false;
                        }
                        requestApi(time);
                    }
                } else {
                    if (nowTime) {
                        if (!o(mobile).val()) {
                            ly.msg('请填写手机号');
                            return false;
                        }
                        requestApi(time)
                    }
                }
            }, 1000));

            function onLoad() {
                var time = getCountdown();
                if (time && time >= 0) startCountdown(time)
            }

            function getCountdown() {
                var diffTime = layui.data(_cacheTable)[cacheKey];
                return diffTime ? parseInt(diffTime, 10) : null;
            }

            function updateCountdown(timeRemaining) {
                o(elem).text('重新发送 (' + timeRemaining + '秒)');
            }

            function startCountdown(time) {
                updateCountdown(time);
                var countdownInterval = setInterval(function () {
                    time--;
                    cache ? layui.data(_cacheTable, {key: cacheKey, value: time}) : '';
                    if (time <= 0) {
                        clearInterval(countdownInterval);
                        cache ? layui.data(_cacheTable, {key: cacheKey, remove: true}) : '';
                        o(elem).text(text);
                        nowTime = true;
                    } else {
                        updateCountdown(time);
                    }
                    typeof callback === 'function' ? callback(time) : '';
                }, 1000);
            }

            function requestApi(time) {
                nowTime = false;
                query = mixed.hasOwnProperty('extra') ? {...mixed.extra, ...{mobile: o(mobile).val()}} : {mobile: o(mobile).val()};
                methods.fetchPost(url, query, function (d) {
                    ly.msg(d.msg);
                    if (d.code === 1) {
                        startCountdown(time);
                    }
                })
            }
        },
        /**
         * 缓存操作
         */
        cache: {
            get: function (key, table = "") {
                return layui.data(table ? table : _cacheTable)[key];
            },
            set: function (key, value, table = "") {
                layui.data(table ? table : _cacheTable, {key: key, value: value})
            },
            remove: function (key, table = "") {
                layui.data(table ? table : _cacheTable, {key: key, remove: true})
            }
        },
    }


    exports('methods', methods);
});